package se.sll.service.catalogue.common.property;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * Laddar de properties som kan användas av applikationen.
 * Dessa properties ska deklareras i java-klasser som implementerar <code>
 * IM1Properties</code>.
 * Properties som finns definierade kan överlagras via en fil: <code>servicecatalogue.properties</code>.
 * Denna fil läggs i en jar-fil som läggs i classpath på servern.
 * 
 * @author Tomas Wenngren, Modul 1
 * @author Jiri Uosukainen
 */
public class M1PropertyLoader
{
    // Håller i samtliga properties för applikationen
    private static Properties applicationProperties = new Properties();

    private static String DOMAIN_PROPERTIES = "servicecatalogue.properties";
    
    public static Properties getApplicationProperties()
    {
        if (applicationProperties.isEmpty())
        {
            List<IM1Properties> propertyFiles = M1PropertyFiles.getPropertyFiles();
            for (IM1Properties propertyFile : propertyFiles)
            {
                applicationProperties.putAll(propertyFile.getProperties());
            }

            // Hämtar ut domänspecifika properties och lägger in dom
            Properties domainProps = loadDomainProperties();
            applicationProperties.putAll(domainProps);
            System.out.println("**** " + applicationProperties.size() + " properties were loaded");
            
        }
        return applicationProperties;
    }

   private static Properties loadDomainProperties()
   {
       Properties domainProps = new Properties();
       try
       {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            domainProps = new Properties();
            InputStream is = loader.getResourceAsStream(DOMAIN_PROPERTIES);
            if (is != null)
            {
                domainProps.load(is);
                System.out.println("**** Properties from " + DOMAIN_PROPERTIES + " was successfully loaded");
                domainProps.storeToXML(System.out, "Domainspecific properties", "UTF-8");
            }
            else
            {
                System.out.println("**** No " + DOMAIN_PROPERTIES + " file was found on classpath, using properties from application");
            }
       }
       catch (Exception ex)
       {
            System.out.println("**** Unable to load properties from " + DOMAIN_PROPERTIES + ", because: ");
            ex.printStackTrace();
       }
       return domainProps;

   }
}